<?php if (!defined('ROBOT')) exit('You can not directly access the file.');

/**
 * 处理功能逻辑
 * @author 亦痕
 * @link http://www.xlogs.cn
 * @version 1.0
 */

if ($action == "req") {
    header("content-type:text/plain; charset=utf-8");
    $result = array();
    $array = json_decode(apiCurl(API_KEY, $_GET['info']), true);
    if ($array) {
        /**
         * 40001 参数key错误
         * 40002 请求内容info为空
         * 40004 当天请求次数已使用完
         */
        if ($array['code'] == 40004) {
            $result['code'] = 0;
            $result['ErrorMsg'] = "请求失败，具体: 当天请求次数已使用完";
            $result['text'] = $array['text'];
        } elseif ($array['code'] == 100000 || $array['code'] == 200000 || $array['code'] == 40002 || $array['code'] == 40001) {
            $result['code'] = 1;
            $result['ErrorMsg'] = "请求成功，状态码: " . $array['code'];
            $result['text'] = $array['text'];
            if ($array['url'] != null) {
                $result['text'] .= ":<br>" . repUrl($array['url']);
            } elseif (is_contain("天气", urldecode($_GET['info'])) && is_contain("° ", $array['text'])) {
                $result['text'] = preg_replace("(:|;)", "<br/>", $array['text']);
            } elseif (is_contain(array("\n", "货物", "【", "】"), $array['text'], true)) {
                $result['text'] = preg_replace("[\\n+]", "<br/>", $array['text']);
            } else {
                $result['text'] = $array['text'];
            }
        } elseif ($array['code'] == 308000) {
            $result['code'] = 1;
            $result['ErrorMsg'] = "请求成功，状态码: " . $array['code'];
            $reply = "亲，已帮您找到菜谱信息:<br/>";
            for ($i = 0; $i < count($array['list']); $i++) {
                $reply .= $array['list'][$i]['name'] . "<br/>";
                //$reply .= $array['list'][$i]['icon'] . "<br/>";
                $reply .= $array['list'][$i]['info'] . "<br/>";
                $reply .= repUrl($array['list'][$i]['detailurl']) . "<br/><br/>";
            }
            $result['text'] = $reply;
        } elseif ($array['code'] == 302000) {
            $result['code'] = 1;
            $result['ErrorMsg'] = "请求成功，状态码: " . $array['code'];
            $reply = "亲，已帮您找到相关新闻:<br/>";
            for ($i = 0; $i < count($array['list']); $i++) {
                if ($array['list'][$i]['article'] != "") {
                    $reply .= $array['list'][$i]['article'] . "<br/>";
                }
                $reply .= repUrl($array['list'][$i]['detailurl']) . "<br/><br/>";
            }
            $result['text'] = $reply;
        } else {
            $result['code'] = 2;
            $result['ErrorMsg'] = "主人还没有给我编写这个功能!";
            $result['text'] = $array['text'];
        }
    } else {
        $result['code'] = 0;
        $result['ErrorMsg'] = "CURL 请求失败，状态码: " . $array['code'];
        $result['text'] = "CURL 请求失败!";
    }
    exit(json_encode($result));
}
?>